<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket 实时通讯</title>
</head>
<body>
<input type="text" id="message" placeholder="输入消息">
<button onclick="sendMessage()">发送</button>
<div id="chat-box"></div>

<script>
    // 创建 WebSocket 连接
    const socket = new WebSocket('ws://localhost:8788');

    // 连接成功时触发
    socket.onopen = function () {
        console.log('连接成功');
    };

    // 接收到消息时触发
    socket.onmessage = function (event) {
        const chatBox = document.getElementById('chat-box');
        const message = document.createElement('p');
        message.textContent = event.data;
        chatBox.appendChild(message);
    };

    // 连接关闭时触发
    socket.onclose = function () {
        console.log('连接已关闭');
    };

    // 发送消息的函数
    function sendMessage() {
        const messageInput = document.getElementById('message');
        const message = messageInput.value;
        if (message) {
            // 发送消息到服务器
            socket.send(message);
            messageInput.value = '';
        }
    }
</script>
</body>
</html>